<template>
<div class="login-container">
  <div class="login-box" >
    <div style="padding: 50px 20px;background-color: white;border-radius: 5px;box-shadow: 0 0 10px rgba(0,0,0,0.2)">
      <el-form ref="formRef" :rules="data.rules"  :model="data.form" style=" width: 350px " >
        <div  style="margin-bottom: 30px;text-align:center;font-size: 24px;color: #0742b1;font-weight: bold">
          欢迎登陆智慧农业大棚系统</div>
        <el-form-item prop="account">
          <el-input  size="large" v-model="data.form.account" placeholder="请输入账号" prefix-icon="User"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input  show-password size="large" v-model="data.form.password" placeholder="请输入密码" prefix-icon="Lock"></el-input>
        </el-form-item>
        <div style="margin-bottom: 20px">
        <el-button @click="Login" size="large" style="width: 100%;color: #0742b1;">登陆</el-button>
        </div>
        <div style="text-align:right;margin-right:2px">还没有账号？请 <a  style="text-decoration: none"href="/register">注册</a></div>
      </el-form>
    </div>

  </div>


</div>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import { User,Lock} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request";

const data =reactive(
    {
      form:{
      },
      rules:{
        account:[
            {required:true,message:'请输入账号',trigger:'blur'},
          {min: 1, max: 16, message: '账号长度应在 1 到 16 个字符之间', trigger: 'blur' }
        ],
        password:[
            {required:true,message:'请输入密码',trigger:'blur'},
          { min: 3, max: 8, message: '密码长度应在 3 到 8 个字符之间', trigger: 'blur' }
        ]

      }


    }

)

const formRef = ref()

onMounted(() => {
  localStorage.clear();
});
const Login =()=>{
  formRef.value.validate((valid)=>{
    if(valid){
      request.post('/User/login',null,{
        params: {
          account: data.form.account,
          password: data.form.password
        }
      }).then(res=>{
        if(res.code === 1){
          //登陆成功
          //存储后台返回的用户数据
          localStorage.setItem("user",JSON.stringify(res.data.data)) //把json对象转换成json字符串存储
          localStorage.setItem("token",JSON.stringify(res.data.token))
          localStorage.setItem("name",JSON.stringify(res.data.data.userName))
          localStorage.setItem("isLogged",JSON.stringify("true"))
          ElMessage.success("登陆成功")
          location.href = '/screen'
        }else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}


</script>

<style scoped>

.login-container{
  height: 100vh;
  overflow: hidden;
  background-image: url("@/assets/bg.jpg");
}
.login-box{

  display: flex;
  align-items: center;
  width: 35%;
  height: 100%;
  bottom: 80px;
  right: 0;
  position: absolute;

}
</style>